package xuwei_k

import javax.servlet.http._

class Main extends HttpServlet {
  import Main._
  
  override def doGet( req:HttpServletRequest,  resp:HttpServletResponse){
    Projects.ALL foreach main
  }
}

object Main{
  
  def main(project:GitProject){
    allCatchPrintStackTrace{
      val x = xml.XML.load(project.commitApiUrl)
      val commits = ( x \\ "commits" \ "commit" ).map{Commit(project)}
      val oldCommits = DB.selectAll(project)
      val newCommits = commits.filterNot{c => oldCommits.contains(c.id)}.toSeq
      DB.insert(project)(newCommits.map{_.id}:_*)
      val client = TweetClient(project)
      newCommits.take(10).foreach{ Thread.sleep(300) ; client.tweet }
    }
  }
}

object Googl{
  import scalaj.http._
  import scala.util.parsing.json.JSON
  
  def getShortUrl(longUrl:String):String = {
    try{
      val data = 
        Http.postData("https://www.googleapis.com/urlshortener/v1/url",
        """{ "longUrl" :  "%s" }""".format(longUrl)    
        ).header("Content-Type","application/json").asString

      JSON.parseFull(data).get.asInstanceOf[scala.collection.Map[String,String]].apply("id")
    }catch{
      case e:Exception => e.printStackTrace
      longUrl
    }
  }
}


